<?php
if(!defined('FROM_INDEX'))exit('Invalid request');

function check_array($array)
{
	return (is_array($array) && count($array) > 0) ? true : false;
}

function get_client_ip()
{
	if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
		$ip = getenv("HTTP_CLIENT_IP");
	else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
		$ip = getenv("REMOTE_ADDR");
	else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
		$ip = $_SERVER['REMOTE_ADDR'];
	else
		$ip = '0.0.0.0';
	return preg_match('/^((25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)\.){3}(25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)$/', $ip) ? $ip : '0.0.0.0';
}

function referer($default = '?')
{
	$DOMAIN = preg_replace("~^www\.~", '', strtolower(getenv('HTTP_HOST') ? getenv('HTTP_HOST') : $_SERVER['HTTP_HOST']));
	
	$referer = isset($_POST['referer']) ? $_POST['referer'] : (isset($_GET['referer']) ? $_GET['referer'] : '');
	
	if($referer == '')$referer = $_SERVER['HTTP_REFERER'];
	
	return $referer;
}

function random($length, $numeric = 0)
{
	mt_srand((double)microtime() * 1000000);
	if($numeric)
	{
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	}
	else
	{
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++)
		{
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

/*
function cut_str($string, $length, $dot = ' ...')
{
	if(strlen($string) <= $length)
	{
		return $string;
	}

	$strcut = '';
	if(CHARSET == 'utf-8')
	{
		$n = $tn = $noc = 0;
		while($n < strlen($string))
		{
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126))
			{
				$tn = 1; $n++; $noc++;
			}
			else if(194 <= $t && $t <= 223)
			{
				$tn = 2; $n += 2; $noc += 2;
			}
			else if(224 <= $t && $t < 239)
			{
				$tn = 3; $n += 3; $noc += 2;
			}
			else if(240 <= $t && $t <= 247)
			{
				$tn = 4; $n += 4; $noc += 2;
			}
			else if(248 <= $t && $t <= 251)
			{
				$tn = 5; $n += 5; $noc += 2;
			}
			else if($t == 252 || $t == 253)
			{
				$tn = 6; $n += 6; $noc += 2;
			}
			else
			{
				$n++;
			}

			if($noc >= $length)
			{
				break;
			}
		}

		if($noc > $length)
		{
			$n -= $tn;
		}

		$strcut = substr($string, 0, $n);
	}
	else
	{
		for($i = 0; $i < $length; $i++)
		{
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	return $strcut.$dot;
}
*/

function cut_string($str, $len)
{
	// 检查长度
	if (mb_strwidth($str, 'UTF-8')<=$len)
	{
		return $str;
	}

	
	// 截取
    $i 		= 0;   
    $tlen 	= 0;   
    $tstr 	= '';   
    
    while ($tlen < $len) 
    {   
        $chr 	= mb_substr($str, $i, 1, 'UTF-8');   
        $chrLen = ord($chr) > 127 ? 2 : 1;   
        
        if ($tlen + $chrLen > $len) break;   
        
        $tstr .= $chr;   
        $tlen += $chrLen;   
        $i ++;   
    }
    
    if ($tstr != $str) 
    {   
        $tstr .= '...';   
    }
    
    return $tstr; 
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
	$ckey_length = 4;
	if(!$key)
    {
		$key = SEC_AUTHKEY;
	}
	
	$key = md5($key);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++)
	{
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++)
	{
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++)
	{
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE')
	{
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
		{
			return substr($result, 26);
		}
		else
		{
			return '';
		}
	}
	else
	{
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

function image_path($id)
{
	$key = "m"."o"."v"."i"."e"."_n"."i"."k"."m";
	$hash = md5($key."\t".$id."\t".strlen($id)."\t".$id % 10);
	$path = $hash{$id % 32} . "/" . abs(crc32($hash) % 100) . "/";

	return $path;
}

function password_hash($date, $password)
{
	$group_key = 'n'.'i'.'k'.'m';
	$validate_pwd = md5($date.'-'.$group_key.'-'.md5($password));
	$validate_pwd = substr($validate_pwd, 24, 3).substr($validate_pwd, 6, 3).substr($validate_pwd, 0, 3).substr($validate_pwd, 12, 3);
	
	return $validate_pwd;
}

function size_convert($filesize)
{
	if ($filesize >= 1073741824)
	{
		$filesize = round($filesize / 1073741824 , 2) . "G";
	}
	else if($filesize >= 1048576)
	{
		$filesize = round($filesize / 1048576, 2) . "M";
	}
	else if($filesize >= 1024)
	{
		$filesize = round($filesize / 1024, 2) . "K";
	}
	else
	{
		$filesize = $filesize . "B";
	}
	
	return $filesize;
}

function js_alert_output($alert_msg, $halt=true)
{
    echo "<script language='javascript'>alert('{$alert_msg}');</script>";
    if($halt)exit;
}

// about 1km
function get_location_range($lat, $lng)
{
	if(!is_numeric($lat) || !is_numeric($lng)) return array(0, 0, 0, 0);
	
	$lat1 = $lat - 0.004;
	$lng1 = $lng - 0.004;
	$lat2 = $lat + 0.004;
	$lng2 = $lng + 0.004;
	
	return array($lat1, $lng1, $lat2, $lng2);
}

function rad($d)
{
	return $d * 3.1415926535898 / 180.0;
}

/**
 * Get distance of two location
 * 
 * @param float $lat1
 * @param float $lng1
 * @param float $lat2
 * @param float $lng2
 * @return distance, the units is 'km'
 */
function get_distance($lat1, $lng1, $lat2, $lng2)
{
	$earth_radius = 6378.137;
	$radLat1 = rad($lat1);
	//echo $radLat1;
	$radLat2 = rad($lat2);
	$a = $radLat1 - $radLat2;
	$b = rad($lng1) - rad($lng2);
	$s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)));
	$s = $s *$earth_radius;
	$s = round($s * 10000) / 10000;
	return $s;
}

function sort_by_dist_asc($a, $b)
{
	$d1 = isset($a['distance']) ? $a['distance'] : 0;
	$d2 = isset($b['distance']) ? $b['distance'] : 0;
	
	if ($d1 == $d2) return 0;
	return ($d1 > $d2) ? -1 : 1;
}